<?php
namespace app\common\controller\Common;

use think\facade\Cache;
use app\common\model\User;
use app\common\model\BonusLog;
use app\common\model\Config;
use think\facade\Db;

class CommonServer
{
     public function pageAction($pre_table_name, $where,$start_size, $post_suffix, $max_suffix, $order = '', $limit = 15){

         $return_data = [
             'list' => [],
             'suffix' => $post_suffix,
             'start_size' => 0,
             'is_bottom' => 1, // 1--到底了；0--还未到底
         ];
         if($post_suffix < 0 || $post_suffix > $max_suffix){
             return $return_data;
         }
         $new_suffix = $suffix = $post_suffix;
         $sur_limit = $limit;
         $bonus_list = [];
         while(1){
             $bonus_list_num = count($bonus_list);
             $sur_limit = $sur_limit - $bonus_list_num;
             if($suffix < 0 || $sur_limit <= 0){
                 break;
             }
             if($new_suffix > $suffix){
                 $start_size = 0;
                 $new_suffix = $suffix;
             }
             $bonus_detail_table = "{$pre_table_name}{$suffix}";
             if(!$this->tableIsExist($bonus_detail_table)){//表格不存在
                 $suffix -= 1;
                 continue;
             }
             $list = Db::name($bonus_detail_table)->where($where)->limit($start_size, $sur_limit)->order($order)->select()->toArray();
             $list_num = count($list);
             $start_size += $list_num;
             if($list_num == 0){
                 $suffix -= 1;
                 continue;
             }elseif($list_num < $sur_limit){
                 $suffix -= 1;
             }

             if(!empty($bonus_list)){
                 $bonus_list = array_merge($bonus_list,$list);
             }else{
                 $bonus_list = $list;
             }
         }

         $is_bottom = 0;
         if($suffix < 0){//到底了
             $is_bottom = 1;
         }
         $return_data = [
             'list' => $bonus_list,
             'suffix' => $suffix,
             'start_size' => $start_size,
             'is_bottom' => $is_bottom,
         ];
         return $return_data;

     }

    /*
    *  判断表格是否存在
    * */
    public function tableIsExist($table){
        if(strpos($table,"kulei_") === false){
            $table = "kulei_".$table;
        }
        if(Db::query('show tables like "'.$table.'"')){
            return true;
        }
        return false;
    }
}
